/*
 * Copyright 2011 Romain Gilles
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jvdb;

import org.slf4j.Logger;

import static org.jvdb.ConfigUtil.LOGGER_BASE_NAME;

/**
 * @author Romain Gilles
 */
abstract class AbstractTimer implements Timer {
    static final String TIMER_LOGGER_NAME = LOGGER_BASE_NAME + ".timer";
    private final Logger statementLogger = Mode.getMode().getLogger();
    private final int connectionId;
    private final int statementId;
    private long start;
    private long end;

    AbstractTimer(int connectionId, int statementId) {
        this.connectionId = connectionId;
        this.statementId = statementId;
    }

    public long start() {
        return start = System.nanoTime();
    }

    public long end() {
        end = System.nanoTime();
        logExec();
        return end;
    }

    private void logExec() {
        if (statementLogger.isInfoEnabled()) {
            String parsedSql = parseSql();
            StringBuilder sb = new StringBuilder(parsedSql.length() + 150);
            sb.append("thread").append(parsedSql).append(" {executed in ").append(end - start).append(" ns (start: ").append(start)
                    .append(" ns, end: ").append(end).append(" ns, connection: ").append(connectionId).append(", statement: ").append(statementId).append(")}");

            statementLogger.info(sb.toString());
        }
    }

    abstract String parseSql();
}
